package cn.akwangl.rocketmq;

import cn.akwangl.common.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * rocketmq 消费者.
 *
 * @author 阿坤同学
 * @date 2022/6/17 22:49
 * @since 0.0.6
 */
@Slf4j
public class Consumer {

    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(Constant.CONSUMER_GROUP);
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        consumer.setNamesrvAddr(Constant.NAMESRV_ADDR);
        consumer.subscribe(Constant.TOPIC_TEST, "*");

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                MessageExt messageExt = msgs.get(0);
                try {
                    String topic = messageExt.getTopic();
                    String tags = messageExt.getTags();
                    String body = new String(messageExt.getBody(), StandardCharsets.UTF_8);

                    log.info("消费者收到消息:topic:{},tags:{},body:{}", topic, tags, body);
                } catch (Exception e) {
                    // 消息重试消费的次数
                    int reconsumeTimes = messageExt.getReconsumeTimes();
                    if (reconsumeTimes == 3) {
                        log.error("消费者发生异常", e);
                        log.error("消息Id:{},messageExt:{}", messageExt.getMsgId(), messageExt);
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();
        log.info("测试消费者启动成功...");
    }
}
